//
//  ZRPictureSelector.m
//  TestFile
//
//  Created by 黄涛 on 2018/7/25.
//  Copyright © 2018年 アポロジャパン. All rights reserved.
//

#import "ZRPictureSelector.h"
#import <Photos/Photos.h>
#import "ZRPictureCollectionViewCell.h"
#import "ZRPictureSelectorModel.h"
#define Tag_bottomBtn 1022
@interface ZRPictureSelector ()<UICollectionViewDelegate,UICollectionViewDataSource,UITableViewDelegate,UITableViewDataSource>

@property (nonatomic , strong) NSMutableArray * dataSource;
@property (nonatomic , strong) NSMutableArray * pictureAlbums;
@property (nonatomic , strong) NSMutableArray * selectedArr;
@property (nonatomic , weak) UICollectionView * mainCollectionView;
@property (nonatomic , weak) UIView * maskView;
@property (nonatomic , weak) UITableView * albumTableView;

/** 底部 预览 确认 背景图 */
@property (nonatomic , weak) UIView * bottomView;

/** 最大选中个数 */
@property (nonatomic , assign) int maxCount;


@end

static NSString * const id_cell = @"ZRPictureCollectionViewCell";
@implementation ZRPictureSelector

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.maxCount = 9;
    
    
    [self setupNavBar];
    [self mainCollectionView];
    [self maskView];
    [self getAlbumsData];
    [self getPicturesData:[self getPictureList].firstObject];
  
    
    [self bottomView];
    
}

#pragma mark - ----------------------- 生命周期 -----------------------
#pragma mark - ----------------------- 其他方法 -----------------------
#pragma mark - 导航条
- (void)setupNavBar{
    
    /** 标题 */
    UIButton * titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    titleBtn.frame = CGRectMake(0, 0, ZRScreenW - 100, 40);
    titleBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    titleBtn.backgroundColor = ZRRandomColor;
    [titleBtn addTarget:self action:@selector(titleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    titleBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [titleBtn setTitle:@"全部" forState:UIControlStateNormal];
    [titleBtn setImage:[UIImage imageNamed:@"m_2_3_1_zhankai_zhankai_icon"] forState:UIControlStateNormal];
    
    self.navigationItem.titleView = titleBtn;
    
    [self.navigationItem.titleView layoutIfNeeded];
    CGFloat tit_w = titleBtn.titleLabel.bounds.size.width;
    CGFloat img_w = titleBtn.imageView.bounds.size.width;
    CGFloat gap = 4;
    [titleBtn setImageEdgeInsets:UIEdgeInsetsMake(0, tit_w + gap, 0, - (tit_w + gap))];
    [titleBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, - (img_w + gap), 0, img_w + gap)];
    


    
    /** 返回按钮 */
    UIButton * backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, 50, 40);
    backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    backBtn.backgroundColor = ZRRandomColor;
    [backBtn setTitle:@"取消" forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnClick:) forControlEvents:UIControlEventTouchUpInside];
     self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    
}

/** 标题点击 */
- (void)titleBtnClick:(UIButton *)sender{
    
    sender.userInteractionEnabled = NO;
    sender.isSelected ? [self hidPictureAlbum] : [self showPictureAlbum];
    sender.selected = !sender.isSelected;
}

/** 返回按钮点击 */
- (void)backBtnClick:(UIButton *)sender{
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 数据
/** 相册数据 */
- (void)getAlbumsData{
    
    NSArray * alubums = [NSArray arrayWithArray:[self getPictureList]];
    [self.pictureAlbums removeAllObjects];
    
    for (PHAssetCollection * as in alubums) {
        
       NSArray * assets = [self getAssetsWithAssetCollection:as ascending:YES];
        
        [self requestImageWithAsset:assets.firstObject size:CGSizeMake((ZRScreenW - 3)/4, (ZRScreenW - 3)/4) resizeMode:PHImageRequestOptionsResizeModeFast completion:^(UIImage *image) {
           
            ZRPictureSelectorModel * model = [[ZRPictureSelectorModel alloc] init];
            model.albumName = as.localizedTitle;
            model.pictureNum = (int)assets.count;
            model.image = image;
            
            [self.pictureAlbums addObject:model];
         
        }];
    }
    
       [self.albumTableView reloadData];
}

/** 图片数据 */
- (void)getPicturesData:(PHAssetCollection *)as{
    
    NSArray * assets = [self getAssetsWithAssetCollection:as ascending:YES];
    [self.dataSource removeAllObjects];
    
    for (PHAsset * asset in assets) {
        
        [self requestImageWithAsset:asset size:CGSizeMake((ZRScreenW - 3)/4, (ZRScreenW - 3)/4) resizeMode:PHImageRequestOptionsResizeModeFast completion:^(UIImage *image) {
            
            ZRPictureSelectorModel * model = [[ZRPictureSelectorModel alloc] init];
            model.image = image;
            
            [self.dataSource addObject:model];
            
        }];
        
    }
    [self.mainCollectionView reloadData];
}



#pragma mark - 判断是否有访问权限
/** 判断是否有相册访问权限 */
+ (BOOL)isPhotoLibraryAllowed{
    
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    return (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) ? NO : YES;
}

/** 判断是否有相机访问权限 */
+ (BOOL)isCameraAllowed{
    
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    return (status == AVAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied) ? NO : YES;
}


#pragma mark - 获取相册列表
- (NSArray *)getPictureList{
    
    NSMutableArray * arr = [NSMutableArray array];
    
    //获取所有智能相册
    PHFetchResult * smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    
    [smartAlbums enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        PHAssetCollection * _Nonnull ac = obj;
        
        //过滤掉视频 和 最近删除
        if (![ac.localizedTitle isEqualToString:@"Recently Deleted"] || ![ac.localizedTitle isEqualToString:@"Videos"]) {
            
            NSArray * assets = [self getAssetsWithAssetCollection:ac ascending:YES];
            
            if (assets.count > 0) [arr addObject:ac];
        }
   
    }];
    
    return arr;
    
}

#pragma mark - 获取指定相册内 所有 图片
- (NSArray <PHAsset *> *)getAssetsWithAssetCollection:(PHAssetCollection *)ac ascending:(BOOL)ascending{
    
    NSMutableArray <PHAsset *> * arr = [NSMutableArray array];
    
    //获取所有 资源，并按 【创建时间】 排序
    PHFetchOptions * options = [[PHFetchOptions alloc] init];
    options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
    
    PHFetchResult *allAssets = [PHAsset fetchAssetsInAssetCollection:ac options:options];
    
    [allAssets enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    
        PHAsset * assetObj = obj;
        
        //判断媒体类型是否为 : 图片
        if (assetObj.mediaType == PHAssetMediaTypeImage ){
            
            [arr addObject:assetObj];
        }
        
    }];
    
    return arr;
}

#pragma mark - 获取 Asset 对应图片
- (void)requestImageWithAsset:(PHAsset *)asset size:(CGSize)size resizeMode:(PHImageRequestOptionsResizeMode)resizeMode completion:(void(^)(UIImage * image))completion{
    
    PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
    /**
     resizeMode：对请求的图像怎样缩放。有三种选择：None，默认加载方式；Fast，尽快地提供接近或稍微大于要求的尺寸；Exact，精准提供要求的尺寸。
     deliveryMode：图像质量。有三种值：Opportunistic，在速度与质量中均衡；HighQualityFormat，不管花费多长时间，提供高质量图像；FastFormat，以最快速度提供好的质量。
     这个属性只有在 synchronous 为 true 时有效。
     */
    option.resizeMode = resizeMode;//控制照片尺寸
    //option.deliveryMode = PHImageRequestOptionsDeliveryModeOpportunistic;//控制照片质量
    //option.synchronous = YES;
    option.networkAccessAllowed = YES;
    //param：targetSize 即你想要的图片尺寸，若想要原尺寸则可输入PHImageManagerMaximumSize
    [[PHCachingImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeAspectFit options:option resultHandler:^(UIImage * _Nullable image, NSDictionary * _Nullable info) {

        completion(image);

    }];
    
    
//    [[PHImageManager defaultManager] requestImageDataForAsset:asset options:option resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
//
//        UIImage * image = [UIImage imageWithData:imageData];
//
//        completion(image);
//
//    }];
    
    
}

#pragma mark - 相册列表动画
/** 弹出动画 */
- (void)showPictureAlbum{     ZRWeakSelf
    
    [self albumTableView];
    self.maskView.hidden = NO;
    
    [self.view layoutIfNeeded];
    [self.albumTableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
    }];
    
    UIButton * titleBtn = (UIButton *)self.navigationItem.titleView;
    
    /** 导航箭头动画 */
    [UIView animateWithDuration:0.4 animations:^{
       titleBtn.imageView.transform = CGAffineTransformMakeRotation(180 * (M_PI /180.0f));
    }];
    
    /** 蒙版颜色动画 */
    [UIView animateWithDuration:0.5 animations:^{
       weakSelf.maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    }];
    
    /** 相册列表动画 */
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:3 options: UIViewAnimationOptionLayoutSubviews animations:^{
        
        [weakSelf.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        
       self.navigationItem.titleView.userInteractionEnabled = YES;
    }];

}

/** 隐藏动画 */
- (void)hidPictureAlbum{    ZRWeakSelf
    
    [self.albumTableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(-ZRScreenH * 0.5);
    }];

    
    UIButton * titleBtn = (UIButton *)self.navigationItem.titleView;
    
    /** 导航箭头动画 */
    [UIView animateWithDuration:0.4 animations:^{
        titleBtn.imageView.transform = CGAffineTransformMakeRotation(0 * (M_PI /180.0f));
    }];
    
    /** 蒙版颜色动画 */
    [UIView animateWithDuration:0.7 animations:^{
        weakSelf.maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
    }];
    
    /** 相册列表动画 */
    [UIView animateWithDuration:0.7 delay:0 usingSpringWithDamping:1 initialSpringVelocity:-6 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        
        [weakSelf.view layoutIfNeeded];

    } completion:^(BOOL finished) {
        
        weakSelf.maskView.hidden = YES;
        self.navigationItem.titleView.userInteractionEnabled = YES;
    }];

}

#pragma mark - 底部图 动画
- (void)showBottomView:(BOOL)isShow{
    
    if (isShow) [self bottomView];
    ZRWeakSelf
    CGFloat y = isShow ? ZRBottomInset : weakSelf.bottomView.height;
    [self.bottomView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(y);
    }];

    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
       
        UIButton * btn = [self.bottomView viewWithTag:Tag_bottomBtn + 1];
        [btn setTitle:[NSString stringWithFormat:@"确定(%d)",(int)self.selectedArr.count] forState:UIControlStateNormal];
    }];
}

#pragma mark - 确定 预览 点击
- (void)bottomBtnClick:(UIButton *)sender{
    
    
    
}

#pragma mark - ----------------------- 代理方法 -----------------------
#pragma mark - Collection Delegate && DataSource
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    ZRPictureCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:id_cell forIndexPath:indexPath];
    
    ZRPictureSelectorModel * model = self.dataSource[indexPath.row];
    cell.model = model;
    cell.backgroundColor =ZRRandomColor;
    
    ZRWeakSelf
    cell.selectdBlock = ^(UIButton *stateBtn) {
      
        if (!stateBtn.isSelected && self.selectedArr.count >= weakSelf.maxCount) return;
        model.isSelected = !stateBtn.isSelected;
        !stateBtn.isSelected ? [self.selectedArr addObject:model] : [self.selectedArr removeObject:model];
      
        if (self.selectedArr.count == 0 && stateBtn.isSelected == YES) {
            
            [self showBottomView:NO];
        }else{
            [self showBottomView:YES];
        }
        
        
        [self.mainCollectionView reloadData];
    };
    
    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    return self.dataSource.count;
}

#pragma mark - TableView Delegate && DataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell * cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    
    ZRPictureSelectorModel * model = self.pictureAlbums[indexPath.row];

    cell.backgroundColor = ZRRandomColor;
    cell.imageView.image = model.image;
    cell.textLabel.text = [NSString stringWithFormat:@"%@ (%d)",model.albumName,model.pictureNum];
    
    return cell;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.pictureAlbums.count;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSArray * albums = [self getPictureList];
    
    [self getPicturesData:albums[indexPath.row]];
    [self hidPictureAlbum];
}



#pragma mark - ----------------------- 活动监听 -----------------------
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    
    [self hidPictureAlbum];
    
    
    
}








#pragma mark - ---------------------- set & get ----------------------
- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [[NSMutableArray alloc] init];
    }
    return _dataSource;
}

- (NSMutableArray *)pictureAlbums{
    if (!_pictureAlbums) {
        _pictureAlbums = [[NSMutableArray alloc] init];
    }
    return _pictureAlbums;
}

- (NSMutableArray *)selectedArr{
    if (!_selectedArr) {
        _selectedArr = [[NSMutableArray alloc] init];
    }
    return _selectedArr;
}


#pragma mark - Picture CollectionView
- (UICollectionView *)mainCollectionView{
    if (!_mainCollectionView) {
        
        CGFloat w = (ZRScreenW - 3) / 4;
        
        UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumLineSpacing = 1;
        flowLayout.minimumInteritemSpacing = 1;
        flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        flowLayout.itemSize = CGSizeMake(w, w);
        
        UICollectionView * mainView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
        [self.view addSubview:mainView];
        mainView.translatesAutoresizingMaskIntoConstraints = NO;
        [mainView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(ZRNavBarHeight);
            make.left.right.mas_equalTo(0);
            make.bottom.mas_equalTo(ZRBottomInset);
        }];
        mainView.pagingEnabled = NO;
        mainView.showsHorizontalScrollIndicator = NO;
        mainView.showsVerticalScrollIndicator = NO;
        mainView.dataSource = self;
        mainView.delegate = self;
        mainView.scrollsToTop = NO;
        
        
       [mainView registerClass:[ZRPictureCollectionViewCell class] forCellWithReuseIdentifier:id_cell];
        
        _mainCollectionView = mainView;
        
    }
    return _mainCollectionView;
}


#pragma mark - 蒙版
- (UIView *)maskView{
    if (!_maskView) {
        
        UIView * maskView = [[UIView alloc] init];
        maskView.translatesAutoresizingMaskIntoConstraints = NO;
        [self.view addSubview:maskView];
        [maskView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(ZRNavBarHeight);
            make.left.right.mas_equalTo(0);
            make.bottom.mas_equalTo(ZRBottomInset);
        }];
        
        _maskView = maskView;
        
    }
    
    return _maskView;
    
}

#pragma mark - 相册列表
- (UITableView *)albumTableView{
    if (!_albumTableView) {
        
        UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        tableView.translatesAutoresizingMaskIntoConstraints = NO;
        [self.maskView addSubview:tableView];
        
        [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.top.mas_equalTo(-ZRScreenH * 0.5);
            make.height.mas_equalTo(ZRScreenH * 0.5);
        }];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.rowHeight = 60;
        tableView.backgroundColor = [UIColor whiteColor];
        _albumTableView = tableView;
    }
    return _albumTableView;
}

#pragma mark - 确认 预览
- (UIView *)bottomView{
    if (!_bottomView) {
        
        UIView * view = [[UIView alloc] init];
        view.translatesAutoresizingMaskIntoConstraints = NO;
        [self.view addSubview:view];
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.height.equalTo(view.mas_width).dividedBy(9.375);
            make.bottom.mas_equalTo(40);
        }];
        
        view.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.9];
        
        NSArray * titles = @[@"预览",@"确定"];
        for (int i = 0; i < titles.count; i++) {
            
            CGFloat btn_w = i == 0 ? 40 : 80;
            UIButton * btn = [[UIButton alloc] init];
            btn.translatesAutoresizingMaskIntoConstraints = NO;
            [view addSubview:btn];
            [btn mas_makeConstraints:^(MASConstraintMaker *make) {
               
                i == 0 ?
                make.left.mas_equalTo(15) : make.right.mas_equalTo(-15);
                make.top.mas_equalTo(3);
                make.bottom.mas_equalTo(-3);
                make.width.mas_equalTo(btn_w);
            }];
            btn.backgroundColor = ZRRandomColor;
            btn.tag = Tag_bottomBtn + i;
            btn.titleLabel.font = [UIFont systemFontOfSize:15];
            [btn setTitle:titles[i] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            
          
        }
        
      _bottomView = view;
    }
    return _bottomView;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
